import os
import yaml
import random
import time
from loguru import logger


# Set service list
service_list = [
    'adservice',
    'cartservice',
    'checkoutservice',
    'currencyservice',
    'emailservice',
    'logservice',
    'paymentservice',
    'productcatalogservice',
    'recommendationservice',
    'shippingservice'
]

# Chaos type
chaos_list = [
    # 'cpu',
    'latency',
    'loss'
]

# Start
total_cnt = 10
interval = 500

# Set exp list
exp_list = []
for i in range(total_cnt):
    while True:
        cur_service = random.choice(service_list)
        cur_chaos = random.choice(chaos_list)

        if (cur_service, cur_chaos) in exp_list:
            continue

        logger.info(f'exp {i}: {cur_service=},{cur_chaos=}')
        exp_list.append((cur_service, cur_chaos))
        break

# Start injection
logger.info('Experiment will be start in 30s...')
time.sleep(30)

for i in range(total_cnt):
    logger.info(f'Start exp {i}...')
    cur_service, cur_chaos = exp_list[i]

    logger.info(f'{cur_service=}, {cur_chaos=}')

    # Set yaml file
    with open(f'templates/{cur_chaos}.yaml', 'rt') as f:
        data = yaml.load(f, Loader=yaml.SafeLoader)

    # Set service name
    data['spec']['selector']['labelSelectors']['app'] = cur_service
    data['metadata']['name'] = f'{cur_service}-{cur_chaos}'

    # Save tmp file
    with open('tmp.yaml', 'wt') as f:
        yaml.dump(data, f, Dumper=yaml.SafeDumper)

    # Apply chaos
    logger.info('Applying chaos tmp.yaml...')
    os.system('kubectl apply -f tmp.yaml')

    logger.info(f'Finished. Wait for {interval}s...')
    time.sleep(interval)
